package com.scanner.hardware;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.scanner.barcodeservice.SerialPortService;
import com.scanner.bean.Constans;
import com.scanner.bean.Event;
import com.scanner.bean.ScanSetting;
import com.scanner.hardware.adapter.ButtonAdapter;
import com.scanner.hardware.db.helper.DaoHelper;
import com.scanner.ui.ChooseCloseScanType;
import com.scanner.ui.ChooseTabSetDialog;
import com.scanner.ui.InputDataScanType;
import com.scanner.ui.ScrollViewListView;
import com.scanner.ui.SelectItemsDialog;
import com.scanner.util.BaseUtils;
import com.scanner.util.LogUtil;
import com.scanner.util.SharePreConfig;
import com.scanner.util.SoundPlayUtil;
import com.suke.widget.SwitchButton;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class JsbSettingActivity extends AppCompatActivity implements SwitchButton.OnCheckedChangeListener , EasyPermissions.PermissionCallbacks{

    @BindView(R.id.btn_setFactory)
    Button btnSetFactory;
    @BindView(R.id.iv_hid)
    ImageView ivHid;
    @BindView(R.id.sb_hid_choose)
    SwitchButton sbHidChoose;
    @BindView(R.id.iv_voice)
    ImageView ivVoice;
    @BindView(R.id.tv_qian)
    TextView tvQian;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.sb_enter_choose)
    SwitchButton sbEnterChoose;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.sb_always_light)
    SwitchButton sbAlwaysLight;
    @BindView(R.id.sb_voice)
    SwitchButton sbVoice;
    @BindView(R.id.rl_addPrefix)
    RelativeLayout rlAddPrefix;
    @BindView(R.id.rl_addSuffix)
    RelativeLayout rlAddSuffix;
    @BindView(R.id.sb_open_boot)
    SwitchButton sbOpenBoot;
    @BindView(R.id.sb_zd_choose)
    SwitchButton sbZdChoose;
    @BindView(R.id.sb_blueTooth_choose)
    SwitchButton sbBlueToothChoose;

    @BindView(R.id.sb_Suspension_btn)
    SwitchButton sbSuspensionBtn;
    @BindView(R.id.rl_Suspension_btn)
    RelativeLayout rlSuspensionBtn;
    @BindView(R.id.rl_choose_voice)
    RelativeLayout rlChooseVoice;
    @BindView(R.id.rl_chooseScanMode)
    RelativeLayout rlChooseScanMode;
    @BindView(R.id.button_list)
    ScrollViewListView buttonListView;
    @BindView(R.id.sb_clipboard_choose)
    SwitchButton sbClipboard;
    @BindView(R.id.sb_openWidget)
    SwitchButton sbWidget;

    private Unbinder bind;
    private DaoHelper daoHelper;
    private ScanSetting scanBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScanSetting settingFormShare = BaseUtils.getSettingFormShare();
        String screenDirection = settingFormShare.getScreenDirection();
        if("Vertical".equalsIgnoreCase(screenDirection)){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制为竖屏
        }else if("Horizontal".equalsIgnoreCase(screenDirection)){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
        }
        setContentView(R.layout.activity_jsb_setting);
        bind = ButterKnife.bind(this);
        daoHelper = new DaoHelper(this);
        initData();
        initView();
    }

    private void initView() {

        btnSetFactory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ScanSetting settingFormShare = BaseUtils.getSettingFormShare();
                int deviceType = settingFormShare.getScanModule();
                Intent intent = new Intent(SerialPortService.BARCODEPORT_WRITEDATA_ACTION);
                if (deviceType == Constans.DTHONEYWELL) {
                    intent.putExtra(SerialPortService.BARCODEPORT_WRITEDATA_EXTRA_DATA, MyApplication.FACTORY_DEFAULT);
                } else if (deviceType == Constans.DTMoToSE655 || deviceType == Constans.DTMoTOSE2707) {
                    daoHelper.deleteAllQR();
                    daoHelper.deleteAllSig();
                    intent.putExtra(SerialPortService.BARCODEPORT_WRITER_FAUDLTE_ACTION, MyApplication.FACTORY_MOTORESULT);
                    MyApplication.getApplication().LoadAllMotoSetting();
                }
                sendBroadcast(intent);
            }
        });
        llBack.setVisibility(View.VISIBLE);
        llBack.setOnClickListener(v -> finish());

        sbVoice.setOnCheckedChangeListener(this);
        sbOpenBoot.setOnCheckedChangeListener(this);
        sbZdChoose.setOnCheckedChangeListener(this);
        sbHidChoose.setOnCheckedChangeListener(this);
        sbEnterChoose.setOnCheckedChangeListener(this);
        sbSuspensionBtn.setOnCheckedChangeListener(this);
        sbClipboard.setOnCheckedChangeListener(this);
        sbWidget.setOnCheckedChangeListener(this);
        sbBlueToothChoose.setOnCheckedChangeListener(this);

        //弃用
        sbAlwaysLight.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                SharePreConfig.setAlwaysLight(isChecked);
                if (isChecked) {
                    Intent intent = new Intent(SerialPortService.BARCODEPORT_WRITEDATA_ACTION);
                    intent.putExtra(SerialPortService.BARCODEPORT_WRITER_WXTAR_BYTRDATA, MyApplication.ALWAYSLINGHTTRUE);
                    sendBroadcast(intent);
                } else {
                    Intent intent = new Intent(SerialPortService.BARCODEPORT_WRITEDATA_ACTION);
                    intent.putExtra(SerialPortService.BARCODEPORT_WRITER_WXTAR_BYTRDATA, MyApplication.ALWAYSLINGHTFALSE);
                    sendBroadcast(intent);
                }
            }
        });
        buttonListView.setFocusable(false);
        ButtonAdapter adapter = new ButtonAdapter(this,scanBean.getBrocastButtons());
        buttonListView.setAdapter(adapter);

    }

    private void initData() {
        boolean alawysLight = SharePreConfig.getAlawysLight();

        scanBean = BaseUtils.getSettingFormShare();
        LogUtil.i("我就看看保存数据对不对=="+ scanBean.toString());
        sbHidChoose.setChecked(scanBean.getHIDChoose());
        sbEnterChoose.setChecked(scanBean.getEnterChoose());
        sbVoice.setChecked(scanBean.getScanVoice());
        sbOpenBoot.setChecked(scanBean.getOpenService_reboot());
        sbZdChoose.setChecked(scanBean.getScanVibrate());
        sbClipboard.setChecked(scanBean.isClipBoardChoose());
        sbWidget.setChecked(scanBean.isWidgetChoose());
        sbAlwaysLight.setChecked(alawysLight);
        sbSuspensionBtn.setChecked(SharePreConfig.getXuanFuKeyScanState());
        sbBlueToothChoose.setChecked(SharePreConfig.getBlueTothScanState());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bind != null) {
            bind.unbind();
        }
    }

    @OnClick({R.id.rl_addPrefix, R.id.rl_addSuffix,R.id.rl_choose_voice, R.id.rl_chooseScanMode,R.id.rl_addTab,R.id.rl_select_baudrate})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_addPrefix:
                InputDataScanType inputDataScanType = InputDataScanType.getInstance(SharePreConfig.getQianzhui(), 1);
                inputDataScanType.show(getSupportFragmentManager(), "qz");
                break;
            case R.id.rl_addSuffix:
                InputDataScanType hzdialog = InputDataScanType.getInstance(SharePreConfig.getHouzhui(), 2);
                hzdialog.show(getSupportFragmentManager(), "hz");
                break;
            case R.id.rl_choose_voice:
                showSingleAlertDialog();
                break;
            case R.id.rl_chooseScanMode:
                ChooseCloseScanType scanType = ChooseCloseScanType.getInstance("");
                scanType.show(getSupportFragmentManager(),"st");
                break;
            case R.id.rl_addTab:
                ChooseTabSetDialog chooseTabSetDialog = ChooseTabSetDialog.getInstance();
                chooseTabSetDialog.show(getSupportFragmentManager(),"ct");
                break;
            case R.id.rl_select_baudrate:
                int baudRate = SharePreConfig.getBaudRate();
                int i = BaseUtils.printArray(Constans.baudRate, String.valueOf(baudRate));
                new SelectItemsDialog(JsbSettingActivity.this, getString(R.string.choose_baud_rate), Constans.baudRate, i, position -> {
                    LogUtil.i("选择的位置="+position+"；选择的波特率="+Constans.baudRate[position]);
                    SharePreConfig.setBaudRate(Integer.parseInt(Constans.baudRate[position]));
                    Event event = new Event(Constans.EVENTCHANGEBAUD,Integer.parseInt(Constans.baudRate[position]));
                    EventBus.getDefault().post(event);
                });
                break;
        }
    }





    private AlertDialog alertDialog; //单选框

    String item = "";
    int pos = SharePreConfig.getVoiceChoosePos();
    int select = SharePreConfig.getVoiceChoosePos();
    public void showSingleAlertDialog() {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle(getString(R.string.voice_choose));
        alertBuilder.setSingleChoiceItems(Constans.voices, pos, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                item = Constans.voices[i];
                pos = i;
                select = i;
            }
        });

        alertBuilder.setPositiveButton(JsbSettingActivity.this.getString(R.string.str_ensure), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog.dismiss();
                SharePreConfig.setVoiceChoosePos(select);
                SoundPlayUtil.init(JsbSettingActivity.this,SharePreConfig.getVoiceChoosePos());//声音初始化
            }
        });

        alertBuilder.setNegativeButton(JsbSettingActivity.this.getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog.dismiss();
            }
        });

        alertDialog = alertBuilder.create();
        alertDialog.show();
    }

/*case R.id.sb_openWidget:控件模式被我抛弃2019年12月19日10:03:05
                if(isChecked && sbHidChoose.isChecked()){
                    sbHidChoose.setChecked(false);
                    settingFormShare.setHIDChoose(false);
                }
                settingFormShare.setWidgetChoose(isChecked);
                BaseUtils.beanToString(settingFormShare);
                break;*/
    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
        LogUtil.d("点击switchBut="+isChecked);
        ScanSetting settingFormShare = BaseUtils.getSettingFormShare();
        switch (view.getId()){
            case R.id.sb_hid_choose:
                settingFormShare.setHIDChoose(isChecked);
                BaseUtils.beanToString(settingFormShare);
                break;

            case R.id.sb_voice:
                settingFormShare.setScanVoice(isChecked);
                BaseUtils.beanToString(settingFormShare);
                break;
            case R.id.sb_enter_choose:
                settingFormShare.setEnterChoose(isChecked);
                BaseUtils.beanToString(settingFormShare);
                break;
            case R.id.sb_open_boot:
                settingFormShare.setOpenService_reboot(isChecked);
                BaseUtils.beanToString(settingFormShare);
                break;
            case R.id.sb_zd_choose:
                settingFormShare.setScanVibrate(isChecked);
                BaseUtils.beanToString(settingFormShare);
                break;
            case R.id.sb_Suspension_btn:
                if(isChecked){
//                    methodRequiresPermission();
                    requestFloatSystem();
                }else {
                    SharePreConfig.setXuanFuKeyScan(false);
                    sendBrocastClose();
                }
                break;
            case R.id.sb_blueTooth_choose:
                SharePreConfig.setBluetoothScan(isChecked);
                break;
            case R.id.sb_clipboard_choose:
                settingFormShare.setClipBoardChoose(isChecked);
                BaseUtils.beanToString(settingFormShare);
                break;
            default:
                break;

        }
    }



    private void sendBrocastOpen(){
        SharePreConfig.setXuanFuKeyScan(true);
        Intent intent = new Intent(SerialPortService.ACTION_FLOAT_SCAN_CODE_SHOW);
        sendBroadcast(intent);
    }

    private void sendBrocastClose(){
        Intent intent = new Intent(SerialPortService.ACTION_FLOAT_SCAN_CODE_CANCEL);
        sendBroadcast(intent);
    }

    private void requestFloatSystem(){
        if (Build.VERSION.SDK_INT >= 23) {
            if (! Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent,10);
            }else {
                //
                sendBrocastOpen();
            }
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        sendBrocastOpen();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        sbSuspensionBtn.setChecked(false);
        LogUtil.i("权限没有");
        if (requestCode == REQUEST_READPHONE_CODE) {
            if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                new AppSettingsDialog.Builder(this)
                        .setRationale("需要悬浮框权限")
                        .setTitle("悬浮框")
                        .build().show();
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 申请权限
     */
    private static final int REQUEST_READPHONE_CODE = 1040;

    @AfterPermissionGranted(REQUEST_READPHONE_CODE)
    public void methodRequiresPermission() {
        String[] perms = {Manifest.permission.SYSTEM_ALERT_WINDOW};
        if (EasyPermissions.hasPermissions(JsbSettingActivity.this, perms)) {
            sendBrocastOpen();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.app_name),
                    REQUEST_READPHONE_CODE, perms);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10) {
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(this)) {
                    sbSuspensionBtn.setChecked(false);
                    Toast.makeText(this,"not granted",Toast.LENGTH_SHORT);
                }else {
                    sendBrocastOpen();
                }
            }
        }
    }

}
/*
*  if("52".equals(deviceNum)){
            rlLeftKey.setVisibility(View.GONE);
            rlFKey.setVisibility(View.GONE);
        }else if("75".equals(deviceNum) || "86".equals(deviceNum) || "16".equals(deviceNum) || "81".equals(deviceNum) || "11".equals(deviceNum)){
            rlLeftKey.setVisibility(View.GONE);
            rlRightKey.setVisibility(View.GONE);
            rlF1Key.setVisibility(View.GONE);
            rlF2Key.setVisibility(View.GONE);
        }else if("62".equals(deviceNum)){
            rlF1Key.setVisibility(View.GONE);
            rlF2Key.setVisibility(View.GONE);
            rlFKey.setVisibility(View.GONE);
        }else {
            rlF1Key.setVisibility(View.GONE);
            rlF2Key.setVisibility(View.GONE);
            rlFKey.setVisibility(View.GONE);
        }*/